﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Web;

namespace Thi_nghiem_nen_ket_co_thong_tin
{
    public partial class Bieu_do_log_cuoi_thi_nghiem : System.Web.UI.UserControl
    {
        protected const string BIEU_DO_LOG_SESSION = "Bieu_do_log_cuoi_thi_nghiem_Data";

        public int NumOfData
        {
            get { return string.IsNullOrEmpty(HnoOfData.Value) ? 0 : Convert.ToInt32(HnoOfData.Value); }
            set { HnoOfData.Value = value.ToString(); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitWebChart();
            }

            dataGridView.DataSource = Session[BIEU_DO_LOG_SESSION];
            dataGridView.DataBind();
        }

        protected void GenData(string str)
        {
            var dt = new DataTable();

            dt.Columns.Add("Id");
            dt.Columns.Add("lucNen");
            dt.Columns.Add("soDoc");
            dt.Columns.Add("heSoRong");

            var input = str.Split('|');
            for (int i = 0; i < input.Length; i++)
            {
                var sub = input[i].Split(';');
                if(sub.Length!=3) continue;
                var dr = dt.NewRow();
                dr[0] = i;
                dr[1] = sub[0];
                dr[2] = sub[1];
                dr[3] = sub[2];
                dt.Rows.Add(dr);
            }
            Session[BIEU_DO_LOG_SESSION] = dt;
            dataGridView.DataSource = dt;
            dataGridView.DataBind();
        }

        protected void ASPxGridView1_BatchUpdate(object sender, DevExpress.Web.Data.ASPxDataBatchUpdateEventArgs e)
        {
        }

        protected void btCompleted_Click(object sender, EventArgs e)
        {
            var abc =
                Regex.Replace(
                    HgridData.Value.Replace("\r", "")
                        .Replace("\t", "")
                        .Replace("\n", "")
                        .TrimStart(';'), "\\;{2,}", ";")
                        .Replace(";|;", "|")
                        .Replace(";|", "|")
                        .Replace("|;", "|");
            GenData(abc);
            var obj = (ObjBieuDoLog) Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION];
            var dt = (DataTable)Session[BIEU_DO_LOG_SESSION];
            if (obj == null||dt==null) return;
            try
            {
                lblErr.Text = "";
                for (int j = 0; j <= obj.i_temp; j++)
                {
                    obj.P_temp[j] = Convert.ToDouble(dt.Rows[j][1]);
                    obj.AH_temp[j] = Convert.ToDouble(dt.Rows[j][2]);
                    obj.hsr_temp[j] = Convert.ToDouble(dt.Rows[j][3]);
                }
                for (int j = obj.i_temp + 1; j <= obj.i_temp + obj.j_temp + 1; j++)
                {
                    if (j + 1 >= dt.Rows.Count) break;
                    obj.P_temp[j] = Convert.ToDouble(dt.Rows[j + 1][1]);
                    obj.AH_temp[j] = Convert.ToDouble(dt.Rows[j + 1][2]);
                    obj.hsr_temp[j] = Convert.ToDouble(dt.Rows[j + 1][3]);
                }
            }
            catch (Exception)
            {
                lblErr.Text = "Dữ liệu đầu vào không đúng định dạng!!";
            }
            Ve_bieu_do();
            Tim_tiep_tuyen_1_2_3();

            double Cc = ((obj.hsr_temp[obj.i_temp - 2] - obj.hsr_temp[obj.i_temp - 1]) / (Math.Log10(obj.P_temp[obj.i_temp - 1]) - Math.Log10(obj.P_temp[obj.i_temp - 2])));
            double Cs = ((obj.hsr_temp[obj.i_temp + 2] - obj.hsr_temp[obj.i_temp + 1]) / (Math.Log10(obj.P_temp[obj.i_temp + 1]) - Math.Log10(obj.P_temp[obj.i_temp + 2])));

            lab_Cc.Text = "Cc = " + Math.Round(Cc, 3).ToString();
            lab_Cs.Text = "Cs = " + Math.Round(Cs, 3).ToString();
            Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION] = obj;

            BindWebChart();
        }

        protected void BindWebChart()
        {
            var obj = (ObjBieuDoLog)Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION];
            if (obj == null) return;
            if (chartControl.Series["series1"] != null)
            {
                chartControl.Series["series1"].Points.Clear();
                //series1.DataSource = obj.Dt1;
                for (int i = 0; i < obj.Dt1.Rows.Count; i++)
                {
                    //series1.Points.Add(new SeriesPoint(i, i));
                    var ag = Convert.ToDouble(obj.Dt1.Rows[i][0]);
                    var vl = Convert.ToDouble(obj.Dt1.Rows[i][1]);
                    if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                        chartControl.Series["series1"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                }
            }

            if (chartControl.Series["series2"] != null)
            {
                chartControl.Series["series2"].Points.Clear();
                //series1.DataSource = obj.Dt1;
                for (int i = 0; i < obj.Dt2.Rows.Count; i++)
                {
                    //series1.Points.Add(new SeriesPoint(i, i));
                    var ag = Convert.ToDouble(obj.Dt2.Rows[i][0]);
                    var vl = Convert.ToDouble(obj.Dt2.Rows[i][1]);
                    if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                        chartControl.Series["series2"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                }
            }

            if (chartControl.Series["series3"] != null)
            {
                chartControl.Series["series3"].Points.Clear();
                //series1.DataSource = obj.Dt1;
                for (int i = 0; i < obj.Dt3.Rows.Count; i++)
                {
                    //series1.Points.Add(new SeriesPoint(i, i));
                    var ag = Convert.ToDouble(obj.Dt3.Rows[i][0]);
                    var vl = Convert.ToDouble(obj.Dt3.Rows[i][1]);
                    if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                        chartControl.Series["series3"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                }
            }

            if (chartControl.Series["series4"] != null)
            {
                chartControl.Series["series4"].Points.Clear();
                //series1.DataSource = obj.Dt1;
                for (int i = 0; i < obj.Dt4.Rows.Count; i++)
                {
                    //series1.Points.Add(new SeriesPoint(i, i));
                    var ag = Convert.ToDouble(obj.Dt4.Rows[i][0]);
                    var vl = Convert.ToDouble(obj.Dt4.Rows[i][1]);
                    if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                        chartControl.Series["series4"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                }
            }

            if (chartControl.Series["series5"] != null)
            {
                chartControl.Series["series5"].Points.Clear();
                //series1.DataSource = obj.Dt1;
                for (int i = 0; i < obj.Dt5.Rows.Count; i++)
                {
                    //series1.Points.Add(new SeriesPoint(i, i));
                    var ag = Convert.ToDouble(obj.Dt5.Rows[i][0]);
                    var vl = Convert.ToDouble(obj.Dt5.Rows[i][1]);
                    if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                        chartControl.Series["series5"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                }
            }

            if (chartControl.Series["series6"] != null)
            {
                chartControl.Series["series6"].Points.Clear();
                //series1.DataSource = obj.Dt1;
                for (int i = 0; i < obj.Dt6.Rows.Count; i++)
                {
                    //series1.Points.Add(new SeriesPoint(i, i));
                    var ag = Convert.ToDouble(obj.Dt6.Rows[i][0]);
                    var vl = Convert.ToDouble(obj.Dt6.Rows[i][1]);
                    if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                        chartControl.Series["series6"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                }
            }

            chartControl.DataBind();
        }

        protected void InitWebChart()
        {
            //bieu do chinh
            var series1 = new Series("Series1", ViewType.ScatterLine);
            chartControl.Series.Add(series1);
            series1.ArgumentScaleType = ScaleType.Numerical;
            series1.ArgumentDataMember = "Argument";
            series1.ValueScaleType = ScaleType.Numerical;
            series1.ValueDataMembers.AddRange(new string[] { "Value" });
            chartControl.Legend.Visible = false;

            // tiep tuyen 1
            var series2 = new Series("series2", ViewType.Line);
            chartControl.Series.Add(series2);
            series2.ArgumentScaleType = ScaleType.Numerical;
            series2.ArgumentDataMember = "Argument";
            series2.ValueScaleType = ScaleType.Numerical;
            series2.ValueDataMembers.AddRange(new string[] { "Value" });
            chartControl.Legend.Visible = false;

            // tiep tuyen 1
            var series3 = new Series("series3", ViewType.Line);
            chartControl.Series.Add(series3);
            series3.ArgumentScaleType = ScaleType.Numerical;
            series3.ArgumentDataMember = "Argument";
            series3.ValueScaleType = ScaleType.Numerical;
            series3.ValueDataMembers.AddRange(new string[] { "Value" });
            chartControl.Legend.Visible = false;

            // tiep tuyen 1
            var series4 = new Series("series4", ViewType.Line);
            chartControl.Series.Add(series4);
            series4.ArgumentScaleType = ScaleType.Numerical;
            series4.ArgumentDataMember = "Argument";
            series4.ValueScaleType = ScaleType.Numerical;
            series4.ValueDataMembers.AddRange(new string[] { "Value" });
            chartControl.Legend.Visible = false;

            // tiep tuyen 1
            var series5 = new Series("series5", ViewType.Line);
            chartControl.Series.Add(series5);
            series5.ArgumentScaleType = ScaleType.Numerical;
            series5.ArgumentDataMember = "Argument";
            series5.ValueScaleType = ScaleType.Numerical;
            series5.ValueDataMembers.AddRange(new string[] { "Value" });
            chartControl.Legend.Visible = false;

            // tiep tuyen 1
            var series6 = new Series("series6", ViewType.Point);
            chartControl.Series.Add(series6);
            series6.ArgumentScaleType = ScaleType.Numerical;
            series6.ArgumentDataMember = "Argument";
            series6.ValueScaleType = ScaleType.Numerical;
            series6.ValueDataMembers.AddRange(new string[] { "Value" });
            chartControl.Legend.Visible = false;

            // Dock the chart into its parent and add it to the current form.
            ((XYDiagram)chartControl.Diagram).AxisX.Title.Visible = true;
            ((XYDiagram)chartControl.Diagram).AxisX.Title.Alignment = StringAlignment.Center;
            ((XYDiagram)chartControl.Diagram).AxisX.Title.Text = "Áp lực nén";
            ((XYDiagram)chartControl.Diagram).AxisX.Title.TextColor = Color.Red;
            ((XYDiagram)chartControl.Diagram).AxisX.Title.Antialiasing = true;
            ((XYDiagram)chartControl.Diagram).AxisX.Title.Font = new Font("Tahoma", 12, FontStyle.Regular);
            // Customize the appearance of the Y-axis title.
            ((XYDiagram)chartControl.Diagram).AxisY.Title.Visible = true;
            ((XYDiagram)chartControl.Diagram).AxisY.Title.Alignment = StringAlignment.Center;
            ((XYDiagram)chartControl.Diagram).AxisY.Title.Text = "Hệ số rỗng";
            ((XYDiagram)chartControl.Diagram).AxisY.Title.TextColor = Color.Blue;
            ((XYDiagram)chartControl.Diagram).AxisY.Title.Antialiasing = true;
            ((XYDiagram)chartControl.Diagram).AxisY.Title.Font = new Font("Tahoma", 12, FontStyle.Regular);

            ((XYDiagram)chartControl.Diagram).AxisY.VisualRange.Auto = true;
            chartControl.DataBind();
        }

        public void LoadData(double[] P, double[] AH, double[] hsr)
        {
            var obj = (ObjBieuDoLog)Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION];
            if (obj ==null)
            {
                obj=new ObjBieuDoLog();
                Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION] = obj;
            }
            obj.i_temp = NumOfData;
            obj.P_temp = P;
            obj.AH_temp = AH;
            obj.hsr_temp = hsr;

            var dt = new DataTable();

            dt.Columns.Add("Id");
            dt.Columns.Add("lucNen");
            dt.Columns.Add("soDoc");
            dt.Columns.Add("heSoRong");

            for (int j = 0; j <= NumOfData; j++)
            {
                var dr = dt.NewRow();
                dr[0] = j;
                dr[1] = P[j];
                dr[2] = AH[j];
                dr[3] = hsr[j];
                dt.Rows.Add(dr);
            }

            var drL = dt.NewRow();
            drL[0] = 999;
            drL[1] = "Giảm tải";
            drL[2] = "Giảm tải";
            drL[3] = "Giảm tải";
            dt.Rows.Add(drL);

            int y = 0;
            int x = NumOfData;
            while (x >= 0)
            {
                var dr = dt.NewRow();
                dr[0] = (NumOfData+y+100);
                dr[1] = P[x];
                dr[2] = AH[x];
                dr[3] = hsr[x];
                dt.Rows.Add(dr);
                y = y + 1;
                x = x - y;
                obj.j_temp = obj.j_temp + 1;
            }

            Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION] = obj;
            Session[BIEU_DO_LOG_SESSION] = dt;
            dataGridView.DataSource = dt;
            dataGridView.DataBind();

        }

        private void Ve_bieu_do()
        {
            var obj = (ObjBieuDoLog)Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION];
            if (obj == null) return;
            obj.Dt1 = new DataTable("Table1");
            obj.Dt1.Columns.Add("Argument", typeof(Double));
            obj.Dt1.Columns.Add("Value", typeof(Double));

            DataRow row = null;

            for (int j = 1; j <= obj.i_temp + obj.j_temp; j++)
            {
                row = obj.Dt1.NewRow();
                row["Argument"] = Math.Log10(obj.P_temp[j]);
                row["Value"] = obj.hsr_temp[j];
                obj.Dt1.Rows.Add(row);
            }
            Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION] = obj;
        }

        private void Tim_tiep_tuyen_1_2_3()
        {
            var obj = (ObjBieuDoLog)Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION];
            if (obj == null) return;
            //<<==================================================================>>//
            double a_1;         //he so toa do duong tiep tuyen 1
            double b_1;
            double[] new_tt1_ordi_1 = new double[2];
            double[] new_tt1_ordi_2 = new double[2];

            double[] goc_nghien = new double[15];
            for (int j = 1; j < obj.i_temp; j++)
                goc_nghien[j] = Math.Atan((obj.hsr_temp[j] - obj.hsr_temp[j + 1]) / (obj.P_temp[j + 1] - obj.P_temp[j])) * 180 / Math.PI;

            for (int j = 0; j <= obj.i_temp; j++)
            {
                if (goc_nghien[j].Equals(goc_nghien.Max()))
                {
                    obj.diem_goc = j;
                    new_tt1_ordi_1[0] = Math.Log10(obj.P_temp[obj.diem_goc]);
                    new_tt1_ordi_1[1] = obj.hsr_temp[obj.diem_goc];
                    new_tt1_ordi_2[0] = Math.Log10(obj.P_temp[obj.diem_goc + 3]);
                    new_tt1_ordi_2[1] = obj.hsr_temp[obj.diem_goc];
                    break;
                }
            }

            a_1 = (new_tt1_ordi_2[1] - new_tt1_ordi_1[1]) / (new_tt1_ordi_2[0] - new_tt1_ordi_1[0]);
            b_1 = new_tt1_ordi_1[1] - new_tt1_ordi_1[0] * a_1;

            obj.Dt2 = new DataTable("Table2");
            obj.Dt2.Columns.Add("Argument", typeof(Double));
            obj.Dt2.Columns.Add("Value", typeof(Double));

            DataRow row2 = null;

            row2 = obj.Dt2.NewRow();
            row2["Argument"] = new_tt1_ordi_1[0];
            row2["Value"] = new_tt1_ordi_1[1];
            obj.Dt2.Rows.Add(row2);
            row2 = obj.Dt2.NewRow();
            row2["Argument"] = new_tt1_ordi_2[0];
            row2["Value"] = new_tt1_ordi_2[1];
            obj.Dt2.Rows.Add(row2);

            //<<==================================================================>>//
            double a_2;         //he so toa do duong tiep tuyen tren
            double b_2;
            double[] old_tt2_ordi_1 = new double[2];
            double[] old_tt2_ordi_2 = new double[2];

            old_tt2_ordi_1[0] = Math.Log10(obj.P_temp[obj.diem_goc]);
            old_tt2_ordi_1[1] = obj.hsr_temp[obj.diem_goc];
            old_tt2_ordi_2[0] = Math.Log10(obj.P_temp[obj.diem_goc + 1]);
            old_tt2_ordi_2[1] = obj.hsr_temp[obj.diem_goc + 1];

            a_2 = (old_tt2_ordi_2[1] - old_tt2_ordi_1[1]) / (old_tt2_ordi_2[0] - old_tt2_ordi_1[0]);
            b_2 = old_tt2_ordi_1[1] - old_tt2_ordi_1[0] * a_2;

            double[] new_tt2_ordi_1 = new double[2];
            double[] new_tt2_ordi_2 = new double[2];

            new_tt2_ordi_1[0] = Math.Log10(obj.P_temp[obj.diem_goc]);
            new_tt2_ordi_1[1] = obj.hsr_temp[obj.diem_goc];
            new_tt2_ordi_2[0] = Math.Log10(obj.P_temp[obj.diem_goc + 3]);
            new_tt2_ordi_2[1] = a_2 * new_tt2_ordi_2[0] + b_2;

            obj.Dt3 = new DataTable("table3");
            obj.Dt3.Columns.Add("Argument", typeof(Double));
            obj.Dt3.Columns.Add("Value", typeof(Double));

            DataRow row3 = null;

            row3 = obj.Dt3.NewRow();
            row3["Argument"] = new_tt2_ordi_1[0];
            row3["Value"] = new_tt2_ordi_1[1];
            obj.Dt3.Rows.Add(row3);
            row3 = obj.Dt3.NewRow();
            row3["Argument"] = new_tt2_ordi_2[0];
            row3["Value"] = new_tt2_ordi_2[1];
            obj.Dt3.Rows.Add(row3);

            //<<==================================================================>>//
            double a_3;         //he so toa do duong phan giac
            double b_3;
            double[] new_tt3_ordi_1 = new double[2];
            double[] new_tt3_ordi_2 = new double[2];

            new_tt3_ordi_1[0] = Math.Log10(obj.P_temp[obj.diem_goc]);
            new_tt3_ordi_1[1] = obj.hsr_temp[obj.diem_goc];

            double a = Math.Atan((obj.hsr_temp[obj.diem_goc] - obj.hsr_temp[obj.diem_goc + 3]) / (Math.Log10(obj.P_temp[obj.diem_goc + 3]) - Math.Log10(obj.P_temp[obj.diem_goc])));
            double b = obj.hsr_temp[obj.diem_goc] - Math.Tan(a / 2) * (Math.Log10(obj.P_temp[obj.diem_goc + 3]) - Math.Log10(obj.P_temp[obj.diem_goc]));

            new_tt3_ordi_2[0] = Math.Log10(obj.P_temp[obj.diem_goc + 3]);
            new_tt3_ordi_2[1] = b;

            a_3 = (new_tt3_ordi_2[1] - new_tt3_ordi_1[1]) / (new_tt3_ordi_2[0] - new_tt3_ordi_1[0]);
            b_3 = new_tt3_ordi_1[1] - new_tt3_ordi_1[0] * a_3;

            obj.Dt4 = new DataTable("table4");
            obj.Dt4.Columns.Add("Argument", typeof(Double));
            obj.Dt4.Columns.Add("Value", typeof(Double));

            DataRow row4 = null;

            row4 = obj.Dt4.NewRow();
            row4["Argument"] = new_tt3_ordi_1[0];
            row4["Value"] = new_tt3_ordi_1[1];
            obj.Dt4.Rows.Add(row4);
            row4 = obj.Dt4.NewRow();
            row4["Argument"] = new_tt3_ordi_2[0];
            row4["Value"] = new_tt3_ordi_2[1];
            obj.Dt4.Rows.Add(row4);
            //<<==================================================================>>//
            double a_4;         //he so toa do duong tiep tuyen duoi
            double b_4;
            double[] old_tt4_ordi_1 = new double[2];
            double[] old_tt4_ordi_2 = new double[2];
            old_tt4_ordi_1[0] = Math.Log10(obj.P_temp[obj.i_temp - 2]);
            old_tt4_ordi_1[1] = obj.hsr_temp[obj.i_temp - 2];
            old_tt4_ordi_2[0] = Math.Log10(obj.P_temp[obj.i_temp - 1]);
            old_tt4_ordi_2[1] = obj.hsr_temp[obj.i_temp - 1];

            a_4 = (old_tt4_ordi_2[1] - old_tt4_ordi_1[1]) / (old_tt4_ordi_2[0] - old_tt4_ordi_1[0]);
            b_4 = old_tt4_ordi_1[1] - old_tt4_ordi_1[0] * a_4;

            double[] new_tt4_ordi_1 = new double[2];
            double[] new_tt4_ordi_2 = new double[2];

            new_tt4_ordi_1[0] = Math.Log10(obj.P_temp[obj.i_temp - 6]);
            new_tt4_ordi_1[1] = (a_4 * new_tt4_ordi_1[0] + b_4);
            new_tt4_ordi_2[1] = old_tt4_ordi_2[1];
            new_tt4_ordi_2[0] = old_tt4_ordi_2[0];

            // Create an empty table.
            obj.Dt5= new DataTable("table5");

            // Add two columns to the table.
            obj.Dt5.Columns.Add("Argument", typeof(Double));
            obj.Dt5.Columns.Add("Value", typeof(Double));

            // Add data rows to the table.
            DataRow row5 = null;

            row5 = obj.Dt5.NewRow();
            row5["Argument"] = new_tt4_ordi_1[0];
            row5["Value"] = new_tt4_ordi_1[1];
            obj.Dt5.Rows.Add(row5);
            row5 = obj.Dt5.NewRow();
            row5["Argument"] = new_tt4_ordi_2[0];
            row5["Value"] = new_tt4_ordi_2[1];
            obj.Dt5.Rows.Add(row5);
            
            //<<==================================================================>>//

            double Pc_x = (b_4 - b_3) / (a_3 - a_4);
            double Pc_y = (b_4 - b_3) / (a_3 - a_4) * a_3 + b_3;

            lab_Pc.Text = "Pc = " + Math.Round(Math.Pow(10, Pc_x), 2).ToString() + " KPa";

            // Create an empty table.
            obj.Dt6 = new DataTable("table6");

            // Add two columns to the table.
            obj.Dt6.Columns.Add("Argument", typeof(Double));
            obj.Dt6.Columns.Add("Value", typeof(Double));

            // Add data rows to the table.
            DataRow row6 = null;

            row6 = obj.Dt6.NewRow();
            row6["Argument"] = Pc_x;
            row6["Value"] = Pc_y;
            obj.Dt6.Rows.Add(row6);
            Session[ObjBieuDoLog.OBJ_BIEU_DO_LOG_SESSION] = obj;
        }
    }
}